package cn.zxd.pub;


import cn.zxd.util.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Properties;
//import javax.mail.*;
//import javax.mail.internet.*;
/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class SendMsgMail {

    public CErrors mErrors = new CErrors();

    private GlobalInput mG = new GlobalInput();

    private TransferData mSendFactor = new TransferData();

    private String mOperate;

    private String Messege;

    private int sendTimes;

    private VData mResult = new VData();

    public SendMsgMail() {

    }

    private boolean getInputData(VData cInputData) {

        mSendFactor = (TransferData) cInputData.getObjectByObjectName(
                "TransferData", 0);

        mG.setSchema((GlobalInput) cInputData.getObjectByObjectName(
                "GlobalInput", 0));

        return true;
    }

    public static void main(String[] args) throws MalformedURLException,
            IOException {

        TransferData PrintElement = new TransferData();
        PrintElement.setNameAndValue("mobile", "22222222222");
        PrintElement.setNameAndValue("content", "果没有氧气。此外，原生生物、真菌中也有些种");
        PrintElement.setNameAndValue("strFrom", "service@picchealth.com");
        PrintElement.setNameAndValue("strTo", "zhangjun@anonymous.com.cn");
        PrintElement.setNameAndValue("strTitle", "无");
        PrintElement.setNameAndValue("strPassword", "");

        GlobalInput tGlobalInput = new GlobalInput();
        tGlobalInput.ComCode = "86";
        tGlobalInput.ManageCom = "86";
        tGlobalInput.Operator = "lands";

        VData aVData = new VData();
        aVData.add(tGlobalInput);
        aVData.add(PrintElement);
        /*
                 String aUserCode = "000011";
                 VData aVData = new VData();
                 aVData.addElement(aUserCode);
         */
        SendMsgMail tSendMsgMail = new SendMsgMail();
        tSendMsgMail.submitData(aVData, "Message");

    }

    public boolean submitData(VData cInputData, String cOperate) throws
            MalformedURLException, IOException {

        cInputData = (VData) cInputData.clone();

        this.mOperate = cOperate;

        if (!getInputData(cInputData)) {

            return false;
        }

        if (mOperate.equals("Message")) {
            try {
                if (!SendMsg()) {

                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                CError cError = new CError();
                cError.moduleName = "SendMsg";
                cError.functionName = "submit";
                cError.errorMessage = e.toString();
                mErrors.addOneError(cError);
                return false;
            }
        }

        if (mOperate.equals("Email")) {

            if (!SendMail()) {

                return false;
            }

        }

        return true;
    }

    /**
     * SendMsg
     *
     * @return boolean
     */
    private boolean SendMsg() throws IOException {
        String sql = "select sysvarvalue from ldsysvar where sysvar = 'MSGArray'";
        ExeSQL mExeSQL = new ExeSQL();
        String ArrPare = mExeSQL.getOneValue(sql);
        String sendsql = "select sysvarvalue from ldsysvar where sysvar = 'SendMsgUrl'";
        String strUrl = mExeSQL.getOneValue(sendsql);
        String numsql = "select sysvarvalue from ldsysvar where sysvar = 'MobileNum'";
        int intMCount = Integer.parseInt(mExeSQL.getOneValue(numsql)) * 12;
        int Arr =  Integer.parseInt(ArrPare);
        String[] mContent = new String[Arr];
        String aMobile = (String) mSendFactor.getValueByName("mobile"); //收件地址
        String content = (String) mSendFactor.getValueByName("content");
        int inttemp = content.length();
        int intContentCount = content.length()/71;
        int intMobilesCount = 0;

//        int bb = aMobile.lastIndexOf(",")+13;
        int bb = aMobile.length();
        intMobilesCount = bb/intMCount;
        String[] StrMobiles= new String[intMobilesCount+1];
        int n=0;
        int intResult = 0;
        String tresult  ="";
        for(int mm=0;mm<=intMobilesCount;mm++)
        {
            if (intMCount*(mm+1)<= bb)
                StrMobiles[mm]= aMobile.substring(intMCount*mm,intMCount*(mm+1)-1);
            else
                StrMobiles[mm] = aMobile.substring(intMCount*mm);
            if (content.length()>=70)
            {
                for (int a = 0; a <= intContentCount; a++) {
                    String tempText1 = "(" + (a + 1) + "/" + (intContentCount + 1) +
                            ")";
                    n = n + tempText1.length();
                    intContentCount = (n + inttemp) / 70;
                    content = tempText1 + content;
                    System.out.println(a + " :" + content.length());
                    System.out.println("length :" + content.substring(0).length());
                    if (content.substring(0).length() >= 70) {
                        mContent[a] = content.substring(0, 70);
                        content = content.substring(70);
                        System.out.println("2 :" + content.length());
                    } else {
                        mContent[a] = content.substring(0, content.length());
                        content = "";
                        System.out.println("3 :" + content.length());
                    }

                }
                String strContentCount = String.valueOf(intContentCount + 1);
                for (int m = 0; m <= intContentCount; m++) {
                    int begin = mContent[m].indexOf("/") + 1;
                    int end = mContent[m].indexOf(")");
                    String strTemp = mContent[m].substring(begin, end);
                    if (strTemp.length() != strContentCount.length() ||
                            !strTemp.equals(strContentCount)) {
                        mContent[m] = mContent[m].substring(0, begin) +
                                strContentCount + mContent[m].substring(end);
                        System.out.println("mContent[" + m + "]: " + mContent[m]);
                    }
                    content = content + mContent[m];
                }
            }
//        String cMsgcontent = StrTool.GBKToUnicode(content); //短信内容
            String cMsgcontent = content;
            String[] MsgText = new String[10]; //超长短信被拆分成标准短信的条数

            try {
                System.out.println("neirong: " + cMsgcontent +
                        "\n tMsgcontent.length: " + content.length());

                int count = 0; //当前是短信的第几个字符
                int beginIndex = 0;
                int total = content.length(); //短信的字符数
                String[] arrayText = new String[total]; //装每个字符的数组

                while (beginIndex < cMsgcontent.length() - 1) {
                    String charecter = cMsgcontent.substring(beginIndex,
                            beginIndex + 1);
//                String tContent = StrTool.GBKToUnicode(charecter);
//                arrayText[count] = URLEncoder.encode(tContent, "UTF-8");
                    arrayText[count] = charecter;
                    beginIndex++;
                    count++;
                }
//            arrayText[count] = URLEncoder.encode(StrTool.GBKToUnicode(
//                    cMsgcontent.substring(count)), "UTF-8"); //最后一个字符的处理
                arrayText[count]=cMsgcontent.substring(count);
                int i = 0;

                sendTimes = cMsgcontent.length() / 71;

                while (i <= sendTimes) {
                    String strTemp = ""; //将字符合并后的UTF字符串
                    for (int j = i * 70; j < 70 * (i + 1); j++) {
                        if (j > count) {
                            break;
                        }
                        if (arrayText[j] == null) {
                            break;
                        }
                        strTemp = strTemp + arrayText[j];
                    }
                    MsgText[i] = strTemp;
                    System.out.println("MsgText[" + i + "] : " + MsgText[i]);
                    i = i + 1;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            int m = 0;
            while (m <= sendTimes) {

//            String strUrl = "http://211.100.6.183/TSmsPortal/smssend"; //?dt="+aMobile+"&feecode=000000&feetype=01&svid=picch&spno=5467&msg="+ MsgText[0] +"&reserve=0000000000000000&type=0";

//            System.out.println("URL : " + strUrl);

                URL url = new URL(strUrl);

                URLConnection connection = url.openConnection();

                connection.setDoOutput(true);

                PrintWriter out = new PrintWriter(connection.getOutputStream());

                System.out.println("msgtext[" + m + "] : " + MsgText[m]);

//            out.print("dt=" + aMobile +
//                      "&feecode=000000&feetype=01&svid=picch&spno=5467&msg=" +
//                      MsgText[m] + "&reserve=0000000000000000&type=0");
                out.print("dt=" + StrMobiles[mm] +
                        "&spid=picch&spno=5467&msg=" + MsgText[m] );
                System.out.println("MsgURL : "+strUrl + "?dt=" + StrMobiles[mm] +
                        "&spid=picch&spno=5467&msg=" + MsgText[m]);
                out.close();

                BufferedReader in;

                StringBuffer response = new StringBuffer();

                try {
                    in = new BufferedReader(new InputStreamReader(connection.
                            getInputStream()));
                }

                catch (IOException ex) {
                    if (!(connection instanceof HttpURLConnection)) {
                        throw ex;
                    }
                    InputStream err = ((HttpURLConnection) connection).
                            getErrorStream();

                    if (err == null) {
                        throw ex;
                    }
                    in = new BufferedReader(new InputStreamReader(err));
                }

                String line;

                while ((line = in.readLine()) != null) {

                    response.append(line + "\n");
                }

                in.close();

                System.out.println("String : " + response.toString());
                System.out.println("response.Len : "+response.length());
                if (response.length()>55)
                    tresult = response.substring(55, 56);
                else
                    tresult = "null";
                System.out.println("result : " + tresult);
                tresult = strCheckReturn(tresult);
                intResult = Integer.parseInt(tresult);
                System.out.println("intResult : "+intResult);
                if( tresult.equals("0"))
                {
                    m = m + 1;
                    if (MsgText[m] == null || MsgText[m].equals("") ||
                            MsgText[m].equals("null")) {
                        break;
                    }
                }
                else
                {
                    if (tresult.equals("1"))
                    {
//                 Messege = "身份验证失败！";
                        Messege = "发送失败!";
                    }
                    else if (tresult.equals("2"))
                    {
                        Messege = "参数错误，parameter的值为错误的参数名!";//"IP地址验证失败！";
                    }
                    else if (tresult.equals("3"))
                    {
                        Messege = "屏蔽字错误!";//"参数不正确！";
                    }
                    else if (tresult.equals("4"))
                    {
                        Messege = "IP地址错误!";//"超过限定的短信数量！";
                    }
                    else if (tresult.equals("5"))
                    {
                        Messege = "时段限制!";//"发送失败！";
                    }
                    else if (tresult.equals("6"))
                    {
                        Messege = "配额不足!";//"发送时间已受限制！";
                    }
                    else if (tresult.equals("7"))
                    {
                        Messege = "发送连接数限制!";//"目的号码在黑名单中！";
                    }
                    else
                    {
                        Messege = "未知问题！";
                    }
                    break;
                }
//            switch (intResult) {
//            case 0:
//                m = m + 1;
//                if (MsgText[m] == null || MsgText[m].equals("") ||
//                    MsgText[m].equals("null")) {
//                    break;
//                }
//                break;
//            case 1:
//                Messege = "身份验证失败！";
//                break;
//            case 2:
//                Messege = "IP地址验证失败！";
//                break;
//            case 3:
//                Messege = "参数不正确！";
//                break;
//            case 4:
//                Messege = "超过限定的短信数量！";
//                break;
//            case 5:
//                Messege = "发送失败！";
//                break;
//            case 6:
//                Messege = "发送时间已受限制！";
//                break;
//            case 7:
//                Messege = "目的号码在黑名单中！";
//                break;
//            default:
//                Messege = "未知问题！";
//                break;
//            }
                System.out.println("222222intResult : "+intResult);
                if (!tresult.equals("0"))
                    m = sendTimes + 1;
            }
        }
        if (!tresult.equals("0")) {
            CError tError = new CError();
            tError.moduleName = "SendMsg";
            tError.functionName = "submitData";
            tError.errorMessage = Messege;
            this.mErrors.addOneError(tError);
            return false;
        }
        return true;

    }

    /**
     * SendMail(支持stmp 和 pop3协议)
     *
     * @return boolean
     */
    private boolean SendMail() {
        return true;
    }/*{
        try {
            //从html表单中获取邮件信息
            String tfrom = (String) mSendFactor.getValueByName("strFrom"); //发件地址

            String tto = (String) mSendFactor.getValueByName("strTo"); ; //收件地址

            String ttitle = StrTool.GBKToUnicode((String) mSendFactor.
                    getValueByName("strTitle")); //主题

            String tcontent = StrTool.GBKToUnicode((String) mSendFactor.
                    getValueByName("content")); //内容
            //从LDSYSVAR表中获取密码，用户名，发送邮件服务
            StringBuffer sql = new StringBuffer(255);
            sql.append(
                    "SELECT SYSVARVALUE FROM LDSYSVAR WHERE SYSVAR='MAIL_SMTP_PASSWORD'");
            String tpassword = (new ExeSQL()).getOneValue(sql.toString());
            sql = new StringBuffer(255);
            sql.append(
                    "SELECT SYSVARVALUE FROM LDSYSVAR WHERE SYSVAR='MAIL_SMTP_USER'");
            String tuser = (new ExeSQL()).getOneValue(sql.toString());
            sql = new StringBuffer(255);
            sql.append(
                    "SELECT SYSVARVALUE FROM LDSYSVAR WHERE SYSVAR='MAIL_SMTP_SERVER'");
            String thost = (new ExeSQL()).getOneValue(sql.toString());
//            String tpassword = (String) mSendFactor.getValueByName(
//                    "strPassword"); //密码
//            String tuser = tfrom.substring(0, tfrom.indexOf("@")); //用户名
//            String thost = "mail." +
//                           tfrom.substring(tfrom.indexOf("@") + 1, tfrom.length()); //mail邮件服务器
//            String thost="smtp."+tfrom.substring(tfrom.indexOf("@")+1,tfrom.length());//smtp邮件服务器

            *//************************************************************************************************//*
            *//*JavaMail需要Properties来创建一个session对象。它将寻找字符串"mail.smtp.host"，属性值就是发送邮件的主机.*//*
            *//*Properties对象获取诸如邮件服务器、用户名、密码等信息，以及其他可在整个应用程序中 共享的信息。            *//*
            *//***********************************************************************************************//*

            Properties props = new Properties();

            props.put("mail.smtp.host", thost); //发送邮件服务器信息

            props.put("mail.smtp.auth", "true"); //同时通过验证

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //这个Session类代表JavaMail 中的一个邮件session. 每一个基于 JavaMail的应用程序至少有一个session但是可以有任意多的session?//
            //Session类定义全局和每个用户的与邮件相关的属性。这此属性说明了客房机和服务器如何交流信息。                                //
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

           *//* Session s = Session.getInstance(props, null); //根据属性新建一个邮件会话

            s.setDebug(true); //设置调试标志,要查看经过邮件服务器邮件命令，可以用该方法

            Message message = new MimeMessage(s); //由邮件会话创建一个对象

            Address from = new InternetAddress(tfrom); //发送人的地址

            message.setFrom(from); //设置发件人

            Address to = new InternetAddress(tto); //接收人的地址

            message.setRecipient(Message.RecipientType.TO, to); //设置收邮件人

            message.setSubject(ttitle); //设置主题

            message.setText(tcontent); //设置内容

            message.setSentDate(new Date()); //设置发件时间

            message.saveChanges(); //设置保存邮件信息*//*

            //////////////////////////////
            // Transport 是用来发送信息的 //
            // 用于邮件的收发打操作。      //
            //////////////////////////////

            System.out.println(
                    "-------------I come in the SendEmailOperate--------------");
            try {

              *//*  Transport transport = s.getTransport("smtp");

                System.out.println("thost :" + thost);

                System.out.println("tuser :" + tuser);

                System.out.println("tpassword :" + tpassword);

                transport.connect(thost, tuser, tpassword); //连接邮箱服务器

                transport.sendMessage(message, message.getAllRecipients()); //发邮件

                transport.close();*//*
            } catch (Exception e) {

                System.out.println("send mail err!");

                return false;
            }
        } catch (MessagingException e) {

            System.out.println(e.toString());

            return false;
        }
        return true;
    }*/
    /**
     *判断返回信息，并且校验
     *@return String
     */
    private String strCheckReturn(String strTemp)
    {
        if (strTemp.equals("0")||strTemp.equals("1")||strTemp.equals("2")||
                strTemp.equals("3")||strTemp.equals("4")||strTemp.equals("5")||
                strTemp.equals("6")||strTemp.equals("7"))
            return strTemp;
        else
            return "9";
    }
    /**
     * SendMail(支持Http协议)
     *
     * @return boolean
     */
    private boolean SendMailHttp() {
        return true;
    }/*{
        try {
            //从html表单中获取邮件信息
            String tfrom = (String) mSendFactor.getValueByName("strFrom"); //发件地址
            String tto = (String) mSendFactor.getValueByName("strTo"); ; //收件地址
            String ttitle = StrTool.GBKToUnicode((String) mSendFactor.
                    getValueByName("strTitle")); //主题
            String tcontent = StrTool.GBKToUnicode((String) mSendFactor.
                    getValueByName("content")); //内容
            String tpassword = (String) mSendFactor.getValueByName(
                    "strPassword"); //密码
            String tuser = tfrom.substring(0, tfrom.indexOf("@")); //用户名

            Properties prop = new Properties();
            //邮件发送者地址
            prop.setProperty("mail.davmail.from", "westmadman@hotmail.com");
            Session ses = Session.getInstance(prop);
            //获得JDAVMail的邮件发送实例
            Transport transport = ses.getTransport("davmail_xmit");
            //连接到Hotmail服务器，请替换为自己的用户名和口令
            transport.connect(null, "westmadman", "miekuang");
            // 准备要发送的邮件
            MimeMessage txMsg = new MimeMessage(ses);
            txMsg.setSubject(ttitle);
            //邮件发送者地址
            InternetAddress addrFrom = new InternetAddress(tfrom);
            txMsg.setFrom(addrFrom);
            //邮件接收者地址
            InternetAddress addrTo = new InternetAddress(tto,
                    tuser);
            txMsg.addRecipient(Message.RecipientType.TO, addrTo);
            //邮件内容
            txMsg.setText(tcontent);
            txMsg.setSentDate(new Date());
            //发送邮件
            transport.sendMessage(txMsg, txMsg.getAllRecipients());
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.toString());
            return false;
        }

        return true;
    }*/
}
